<?php

namespace backend\controllers;

use app\models\AsrAkf;
use app\models\AsrAudio;
use app\models\AsrAudioClassify;
use app\models\AsrFiles;
use app\models\AsrKeyword;
use app\models\AsrKeywordClassify;
use app\models\AsrKeywordEndClassify;
use app\models\AsrKeywordXtlcClassify;
use app\models\AsrKeywordYwlcClassify;
use app\models\search\AsrAudioSearch;
use function array_diff;
use function array_slice;
use common\helps\Tools;
use common\helps\UploadFiles;
use Yii;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;
use yii\web\UploadedFile;
use function explode;
use function file_exists;
use function json_encode;
use function unlink;

/**
 * AsrAudioController implements the CRUD actions for AsrAudio model.
 */
class AsrAudioController extends CommonController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * 业务流程，查询出来了所有的左边以及右边的数据
     * 默认情况下是显示第一个业务流程
     * $id 为流程id  audio_id=71
     */
    public function actionProfession($id,$classify = "app\models\AsrKeywordYwlcClassify")
    {
        //没有传递流程ID过来
        //拿到第一个默认显示的流程id
        $lc = (new $classify())->find()->where("parent_id>0")->orderBy("parent_id")->orderBy("id")->one();
        //查找出来左边的所有的数据
        $nodeList = $this->findNodeList($id);
        $fileList = '';
        $intentList = '';
        if (!empty($lc)){
            //查找出来所有的文件列表
            $fileList = $this->findFileList($lc->file_id);
            //查找出所有的意图列表
            $intentList = $this->findIntentList($lc->id);
        }
        return $this->render('profession', [
            'id' => $id,
            'lc' => $lc,
            'nodeList' => $nodeList,
            'fileList' => $fileList,
            'intentList' => $intentList,//就是asrKeyword表的数据
        ]);
    }

    /**
     * 业务流程，查询出来了所有的左边以及右边的数据
     * 默认情况下是显示第一个业务流程
     * $id 为流程id  audio_id=71
     */
    public function actionSystem($id,$classify = "app\models\AsrKeywordXtlcClassify")
    {
        //没有传递流程ID过来
        //拿到第一个默认显示的流程id
        $lc = (new $classify())->find()->where("id>1")->orderBy("id")->one();
        //查找出来左边的所有的数据
        $nodeList = $this->findSystemNodeList($id);
        $fileList = '';
        $intentList = '';
        if (!empty($lc)){
            //查找出来所有的文件列表
            $fileList = $this->findFileList($lc->file_id);
            //查找出所有的意图列表
            $intentList = $this->findIntentList($lc->id);
        }
        return $this->render('system', [
            'id' => $id,
            'lc' => $lc,
            'nodeList' => $nodeList,
            'fileList' => $fileList,
            'intentList' => $intentList,//就是asrKeyword表的数据
        ]);
    }

    /**
     * 根据audio_id查找所有的流程分类，再根据流程分类得到树形结构
     * 得到的树形结构的数组
     */
    public function findSystemNodeList($id,$classify = "app\models\AsrKeywordXtlcClassify"){
        $lc = $classify::find()->orderBy("id")->all();
        $classify = new $classify();
        $lc = $classify->getTree(ArrayHelper::toArray($lc));
        return $lc;
    }


    public function actionSaveLc($id,$classify = "app\models\AsrKeywordYwlcClassify"){
        $data = json_decode($_POST['data']);
        $lc = $classify::findOne($id);
        $res = $lc->updateAttributes(['name'=>$data->name,'intent_score'=>$data->intent_score,'keywords'=>$data->keywords]);
        if ($res){
            echo $this->success([]);
            exit();
        }else{
            echo "faild";
            exit();
        }
    }
    public function actionDeleteLc($id,$classify = "app\models\AsrKeywordYwlcClassify"){
        $lc = $classify::findOne($id);
        $parent_id_num = (int)(new  AsrKeywordYwlcClassify)->find()->where("parent_id=".$lc->parent_id)->count();
        if ($parent_id_num<=1){
            echo $this->error("只有一个子节点，不能删除！");
            exit();
        }else{
            $res = $classify::deleteAll(['id'=>$id]);
            if ($res){
                echo $this->success([]);
                exit();
            }else{
                echo "faild";
                exit();
            }
        }

    }

    /**
     * 业务流程 单单是查询出来了左边的数据
     * id 为  audio_id
     */
    public function actionFindNodeList($id,$classify = "app\models\AsrKeywordYwlcClassify"){
        echo $this->success($this->findNodeList($id,$classify));
        exit();
    }

    /**
     * 新增业务流程节点
     */
    public function actionAddNode($classify = "app\models\AsrKeywordYwlcClassify")
    {
        $new_node = new $classify();
        $data = json_decode($_POST['data']);
        $new_node->audio_id = $data->audio_id;
        $new_node->intent_score = 0;
        if (isset($data->parent_id) && $data->parent_id!=0){
            $new_node->parent_id = $data->parent_id;
            $new_node->name = "新的子节点";
            if($new_node->save()){
                $res = $new_node->attributes;
                echo $this->success($res);
                exit();
            }
        }else{
            $new_node->parent_id = 0;
            $new_node->name = "新的父节点";
            $new_node->save();
            $son_node = new $classify();
            $son_node->parent_id = $new_node->attributes['id'];
            $son_node->audio_id = $data->audio_id;
            $son_node->name = "新的子节点";
            $son_node->intent_score = 0;
            if($son_node->save()){
                $res = $son_node->attributes;
                echo $this->success($res);
                exit();
            }
        }
    }


    /**
     * @param $id 流程 id lc_id
     */
    public function actionFindLc($id,$classify = "app\models\AsrKeywordYwlcClassify"){
        //有传递流程ID过来
        $lc = (new $classify())->find()->where("id=".$id)->one();
        echo $this->success($lc);
    }

    /**
     *文件列表查询
     * id 为 流程id lc_id
     */
    public function actionFindFileList($id,$classify = "app\models\AsrKeywordYwlcClassify"){
        $file = $classify::findOne($id);
        echo $this->success($this->findFileList($file->file_id));
        exit();
    }

    /**
     * 文件上传的方法
     */
    public function actionUploadfile($files_id,$content,$audio_id,$lc_id,$classify = "app\models\AsrKeywordYwlcClassify"){
        $basePath = Yii::$app->basePath;
        // r拿到年月的时间
        $timePath = date('y/md/', time());
        $filePath = $basePath . '/web/uploads/yuyin/' . $timePath;
        // 通过时间年月来创建文件夹
        Tools::mkdirs($filePath);
        if (!empty($_FILES)) {
            $tempFile = $_FILES['file']['tmp_name'];
            $randomName = Tools::randName();
            // 验证文件类型
            $fileTypes = array('wav');
            $fileParts = pathinfo($_FILES['file']['name']);
            //改变文件名字
            $targetFile = $filePath  . time() . $randomName .".".$fileParts['extension'];
            $response = array ();
            if (in_array($fileParts['extension'],$fileTypes)) {
                //移到相应的文件夹内
                move_uploaded_file($tempFile,$targetFile);
                //将文件信息存入数据库
                if (!empty($files_id)){//文件ID不为空，为更新文件，就要删除原来的文件，然后再上传
                    $fileModel = AsrFiles::findOne($files_id);
                    unlink(".".$fileModel->filepath);//文件删除成功,删除原来的文件
                }else{//文件ID为空，为新增文件
                    $fileModel = new AsrFiles();
                }
                $fileModel->name = $_FILES['file']['name'];
                $fileModel->filepath = '/uploads/yuyin/' . $timePath . time() . $randomName .".".$fileParts['extension'];
                $fileModel->filesize = $_FILES['file']['size'];
                $fileModel->create_time = time();
                $fileModel->user = Yii::$app->user->id;
                $fileModel->content = $content;
                $fileModel->audio_id = $audio_id;
                if($fileModel->save()){//文件保存成功，后就要更新业务流程内容了
                    if (empty($files_id)){//如果是新增的文件以及文件内容，就要更新业务流程的内容
                        $parms['file_id'] = $classify::findOne($lc_id)->file_id.','.$fileModel->files_id;//文件的id进行拼接
                        $this->updateLc($lc_id,$parms,$classify);
                    }
                    $response['success'] = 1;
                    foreach ($fileModel->attributes as $key => $value){
                        $response[$key] = $value;
                    }
                    echo json_encode($response);
                }else{
                    $response['success'] = 0;
                    $response['error'] = '无效的文件类型';
                    echo json_encode($response);
                }
            } else {
                $response['success'] = 0;
                $response['error'] = '无效的文件类型';
                echo json_encode($response);
            }
        }
        exit();
    }

    /**
     * 文件删除的方法
     */
    public function actionDeleteFiles($files_id,$audio_id,$lc_id,$classify="app\models\AsrKeywordYwlcClassify"){
        if (!empty($files_id)){//文件ID不为空，为删除该id的文件
            $fileModel = AsrFiles::findOne($files_id);
        }
        $filepath = $fileModel->filepath;
        if(AsrFiles::deleteAll(['files_id'=>$files_id])){
            if (unlink(".".$filepath)){//文件删除成功，就要更新ywlc的content
                $parms['file_id'] = str_replace(",".$files_id,"",$classify::findOne($lc_id)->file_id);//文件的id进行删除
                $this->updateLc($lc_id,$parms,$classify);
                $res = '';
                echo $this->success($res);
                exit();
            }else {
                echo "faild";
            }
        }else {
            echo "faild";
        }
        exit();
    }
    /**
     *
     */
    public function actionFindIntentList($id){
        echo $this->success($this->findIntentList($id));
        exit();
    }

    /**
     * 新增业务流程节点
     */
    public function actionAddIntent()
    {
        $data = json_decode($_POST['data']);
        $asrKeyword = new AsrKeyword();
        $asrKeyword->intent_name = $data->intent_name;
        $asrKeyword->content = $data->content;
        $asrKeyword->classify_id = $data->classify_id;
        $asrKeyword->classify_type = $data->classify_type;
        if ($asrKeyword->save()){
            echo $this->success($asrKeyword->attributes);
        };
        exit();
    }

    /**
     * 删除意图数据
     * Asrkeyword表的id
     */
    public function actionDeleteIntent($id)
    {
        $result = AsrKeyword::deleteAll(['keyword_id'=>$id]);
        if ($result){
            echo $this->success([]);
        };
        exit();
    }


    /**
     * 通过关键字ID查到关键字以及其
     * 文件列表
     * @param $id
     */
    public function actionFindNextIntent($id){
        $keyword = $this->findNextIntent($id);
        $data['file_arr'] = $this->findIntentFilelist($keyword->next_classify_type,$keyword->next_classify_id);
        $data['next_intent'] = $keyword->attributes;
        echo $this->success($data);
        exit();
    }

    public function  actionFindAllIntent($typeid){
        $data['all_intent'] = ArrayHelper::toArray($this->findAllIntent($typeid));
        echo $this->success($data);
        exit();
    }

    /**
     * 保存keyword
     */
    public function actionSaveNextIntent($id,$next_classify_type,$next_classify_id){
        $asrKeyword = AsrKeyword::findOne($id);
        $asrKeyword->next_classify_type = $next_classify_type;
        $asrKeyword->next_classify_id = $next_classify_id;
        if ($data = $asrKeyword->save()){
            echo $this->success($data);
            exit();
        }
    }

    /**
     * 通过关键字ID查到关键字以及其
     * 文件列表
     * @param $id
     */
    public function actionFindIntentFilelist($next_classify_type,$next_classify_id){
        echo $this->success($this->findIntentFilelist($next_classify_type,$next_classify_id));
        exit();
    }

    /**
     * 通过type查找所有的父为0的节点
     * @param $typeid
     * @return AsrKeyword|null
     */
    public function findAllIntent($typeid ){
        switch ($typeid){
            case 0:
                $classify = (new AsrKeywordClassify())->find()->all();
                break;
            case 1:
                $classify = (new AsrKeywordYwlcClassify())->find()->all();
                break;
            case 2:
                $classify = (new AsrKeywordXtlcClassify())->find()->all();
                break;
            case 3:
                $classify = (new AsrKeywordEndClassify())->find()->all();
                break;
        }
        return $classify;
    }

    /**
     * 根据audio_id查找所有的流程分类，再根据流程分类得到树形结构
     * 得到的树形结构的数组
     */
    public function findNodeList($id,$classify = "app\models\AsrKeywordYwlcClassify"){
        if (empty($id)){
            $lc = $classify::find()->orderBy("id")->all();
        }else{
            $lc = $classify::find()->where(['audio_id'=>$id])->orderBy("id")->all();
        }
        $classify = new $classify();
        $lc = $classify->getTree(ArrayHelper::toArray($lc));
        return $lc;
    }

    /**
     * 查找id串内的文件列表
     * 是文件数组
     */
    public function findFileList($file_id){
        if (!empty($file_id)){
            $file_ids = $file_id;//文件的id列表
            $file_ids = rtrim($file_ids, ",");
            $files = AsrFiles::findAll(explode(",",$file_ids));
        };
        $filesArr = [];
        if(!empty($files)){
            $filesArr = ArrayHelper::toArray($files);
        }
        return $filesArr;
    }

    /**
     * 拿到右边的识别意向的数据库数组
     * @param $id
     * @param $ywlc_id
     * @return mixed
     * 返回的是asrKeyword表的数组列表
     */
    public function findIntentList($lc_id){
        //拿到识别意向的所有数据
        $asrKeyword = AsrKeyword::findAll(['classify_id'=>$lc_id]);
        $asrKeywordArr = [];
        if (!empty($asrKeyword)){
            $asrKeywordArr = ArrayHelper::toArray($asrKeyword);
        }
        return $asrKeywordArr;
    }

    /**
     * 业务流程 单单是查询出来了右边的数据
     */
    public function findProfessionRight($id,$lc_id,$classify = "app\models\AsrKeywordYwlcClassify"){
        $lc = $classify::findOne(['id'=>$lc_id]);
        if (!empty($lc)){
            $filesArr = $this->findFileList($lc->file_id);
        }
        $res['Info'] = ArrayHelper::toArray($lc);//业务流程的数组数据
        $res['Sounds'] = $filesArr;//语音文件的数组
        $res['Intents'] = $this->findProfessionRightIntent($lc);//语音文件的数组
        return $res;
    }

    /**
     * @param $lc_id更新流程信息
     */
    public function updateLc($lc_id,$parms,$classify="app\models\AsrKeywordYwlcClassify"){
        $classifyModel = $classify::findOne($lc_id);
        $classifyModel->updateAttributes($parms);
    }

    public function findIntentFilelist($next_classify_type,$next_classify_id){
        switch ($next_classify_type){
            case 0:
                $classify = AsrKeywordClassify::findOne($next_classify_id);
                break;
            case 1:
                $classify = AsrKeywordYwlcClassify::findOne($next_classify_id);
                break;
            case 2:
                $classify = AsrKeywordXtlcClassify::findOne($next_classify_id);
                break;
            case 3:
                $classify = AsrKeywordEndClassify::findOne($next_classify_id);
                break;
        }
        if (!empty($classify->file_id)){
            $file_id = $classify->file_id;
        }else{
            $file_id = "-1";
        }
        //文件的列表数组
        $file_arr = $this->findFileList($file_id);
        return $file_arr;
    }

    /**
     * 通过id查找关键字
     */
    public function findNextIntent($id){
        return AsrKeyword::findOne($id);
    }


    public function actionFindNextKeywordIntent($id){
        $asrKeyword = AsrKeyword::findOne($id);
        echo $this->success($asrKeyword);
        exit();
    }

    /**
     * @param $id
     * 保存下一步的关键字
     */
    public function actionSaveKeywordIntent($id){
        $content = json_decode($_POST['data']);
        $asrKeyword = AsrKeyword::findOne($id);
        if($asrKeyword->updateAttributes(['content'=>$content->content])){
            echo $this->success([]);
            exit();
        }else{
            echo "failed";
            exit();
        }
    }

    /**
     * 成功后处理的方法
     * @param $arr
     * @return mixed
     */
    public function success($arr){
        $res['Result'] = "success";
        if (!is_array($arr)){
            $arr = ArrayHelper::toArray($arr);
        }
        $res['Data'] = $arr;
        return json_encode($res);
    }
    /**
     * 失败后处理的方法
     * @param $arr
     * @return mixed
     */
    public function error($arr){
        $res['Message'] = $arr;
        return json_encode($res);
    }
















    /**
     * 结束流程
     */
    public function actionEnd($id){
        return $this->render('end', [
            'id' => $id,
        ]);
    }

    public function actionEndpost(){

        $id = $_POST['id'];
        if(empty($_POST['keyword_classify_end_id'])) {
            $mainSystem = AsrKeywordEndClassify::find()->where(['audio_id' => null])->orWhere(['audio_id' => $id])->asArray()->all();
            $file_id = explode(',', $mainSystem[0]['file_id']);
            foreach ($file_id as $value) {
                $file[] = AsrFiles::find()->where(['files_id' => $value])->asArray()->one();
            }
            $data['mainSystem'] = $mainSystem;
            $data['file'] = $file;
            $data['id'] = $id;
            echo json_encode($data);
        }
        else{
                //当前节点
                $current = AsrKeywordEndClassify::find()->where(['keyword_classify_end_id' => $_POST['keyword_classify_end_id']])->asArray()->one();
                //文件
                $file_id = explode(',', $current['file_id']);
                foreach ($file_id as $value) {
                    $file[] = AsrFiles::find()->where(['files_id' => $value])->asArray()->one();
                }
                $data['file'] = $file;
                $data['current'] = $current;
                echo $this->success($data);
            }
    }

    /**
     * 删除结束流程节点
     */
    public function actionEnddel()
    {
        $result = AsrKeywordEndClassify::findOne($_POST['keyword_classify_end_id']);
        if(!empty($result->file_id)){
            $file_id = explode(',', $result->file_id);
            foreach ($file_id as $value){
                $res = AsrFiles::findOne($value);
                if(file_exists(Yii::$app->basePath . "/web".$res->filepath)){
                    unlink(Yii::$app->basePath . "/web".$res->filepath);
                }
                $file[] = $res->delete();
            }
            foreach ($file as $value){
                if($value==1){
                    $v = 1;
                }
            }
            if($v == 1 && AsrKeywordEndClassify::findOne($_POST['keyword_classify_end_id'])->delete()){
                echo 1;
            }
        } else{
            if(AsrKeywordEndClassify::findOne($_POST['keyword_classify_end_id'])->delete()){
                echo 1;
            }
        }
    }
    /**
     * 添加结束流程节点
     */

    public function actionEndadd()
    {
        $new_node = new AsrKeywordEndClassify();
        $new_node->audio_id = $_POST['audio_id'];
        $new_node->name = '新的节点';
        if($new_node->save()){
            $id = $_POST['audio_id'];
            $mainSystem = AsrKeywordEndClassify::find()->where('audio_id is null')->orWhere(['audio_id'=>$id])->asArray()->all();
            echo $this->success($mainSystem);
        }
    }

    /*
     * 结束文件上传
     */
    public function actionEndupload()
    {
        //file_id是否存在
        if ($_POST['file_id']=='undefined' || empty($_POST['file_id'])){
            $file = new AsrFiles();
            $file->name = $_FILES['filename']['name'];
            $file->filepath = $_FILES['filename']['name'];
            $file->filesize = $_FILES['filename']['size'];
            $file->create_time = time();
            $file->user = Yii::$app->user->id;
            $file->audio_id = $_POST['audio_id'];

            //文件上传存放的目录
            $dir = Yii::$app->basePath . "/web/uploads/yuyin/" . date("y") . '/' . date("md") . '/';
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
            }
            $names = time() . '_' . $_FILES['filename']['name'];
            $file->filepath = "/uploads/yuyin/" . date("y") . '/' . date("md") . "/" . $names;
            $result = AsrKeywordEndClassify::findOne($_POST['keyword_classify_end_id']);

            if (move_uploaded_file($_FILES['filename']['tmp_name'], $dir . $names) && $file->save()) {
                $last_id = Yii::$app->getDb()->lastInsertID;
                if(!empty($result->file_id)){
                    $file_id = explode(',',$result->file_id);
                    array_push($file_id,$last_id);
                    $result->file_id = join(',', $file_id);
                } else{
                    $result->file_id = $last_id;
                }
                if($result->save()){
                    $key = AsrKeywordEndClassify::findOne($_POST['keyword_classify_end_id']);
                    $file_id = explode(',',$key->file_id);
                    foreach ($file_id as $value){
                        $ff[] = AsrFiles::find()->where(['files_id'=>$value])->asArray()->one();
                    }
                    echo $this->success($ff);
                }
            }
        }else{
            //录音文件已经存在
            $files = AsrFiles::findOne($_POST['file_id']);
            if($files->filepath) {
                if (file_exists(Yii::$app->basePath . "/web" . $files->filepath)) {
                    if(!empty($files->filepath)){
                        unlink(Yii::$app->basePath . "/web" . $files->filepath);
                    }
                }
            }
            $files->filesize = $_FILES['filename']['size'];
            $files->name = $_FILES['filename']['name'];
            $files->user = Yii::$app->user->id;
            //文件上传存放的目录
            $dir = Yii::$app->basePath . "/web/uploads/yuyin/" . date("y") . '/' . date("md") . '/';
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
            }
            $name = time() . '_' . $_FILES['filename']['name'];
            $files->filepath = "/uploads/yuyin/" . date("y") . '/' . date("md") . "/" . $name;

            if (move_uploaded_file($_FILES['filename']['tmp_name'], $dir . $name) && $files->save()) {
                $key = AsrKeywordEndClassify::findOne($_POST['keyword_classify_end_id']);
                $file_id = explode(',',$key->file_id);
                foreach ($file_id as $value){
                    $ff[] = AsrFiles::find()->where(['files_id'=>$value])->asArray()->one();
                }
                echo $this->success($ff);
            }
        }
    }

    /**
     *结束保存
     */
    public function actionSaveclassifyend()
    {
        $keyword_classify_end_id = $_POST['keyword_classify_end_id'];
        $result = AsrKeywordEndClassify::findOne($keyword_classify_end_id);
        $result->name = $_POST['name'];
        $result->intent_score = $_POST['score'];
        if(empty($result->file_id)){
            foreach($_POST['content'] as $key=>$v){
                $result = AsrKeywordEndClassify::findOne($keyword_classify_end_id);
                $result->name = $_POST['name'];
                $result->intent_score = $_POST['score'];
                if(empty($file_id)){
                    $file_id = [];
                }else{
                    $file_id = explode(',',$result->file_id);
                }
                $file = new AsrFiles();
                $file->content = $v;
                $file->create_time = time();
                $file->user = Yii::$app->user->id;
                $file->audio_id = $_POST['id'];
                $file->save();
                $last = Yii::$app->getDb()->lastInsertID;
                array_push($file_id,$last);
                $result->file_id = join(',', $file_id);
                $result->save();
            }

            $id = $_POST['id'];
            $mainSystem = AsrKeywordEndClassify::find()->where(['audio_id'=>null])->orWhere(['audio_id'=>$id])->asArray()->all();
            $file_ids = explode(',',$result->file_id);
            foreach ($file_ids as $value){
                $f[] = AsrFiles::find()->where(['files_id'=>$value])->asArray()->one();
            }
            $result = AsrKeywordEndClassify::find()->where('keyword_classify_end_id='.$keyword_classify_end_id)->asArray()->one();
            $data['current'] = $result;
            $data['mainSystem'] = $mainSystem;
            $data['file'] = $f;
            echo $this->success($data);

        }
        else{
            $file_id = $result->file_id;
            $file_id = explode(',',$file_id);
            if(count($_POST['content'])>count($file_id)){
                foreach($file_id as $key=>$v){
                    $file = AsrFiles::findOne($v);
                    if(!empty($file)){
                        $file->content = $_POST['content'][$key];
                        $file->save();
                    }
                }
                $count = count($_POST['content'])-count($file_id);
                for($i=0; $i<$count; $i++){
                    $files = new AsrFiles();
                    $files->content = array_slice($_POST['content'],count($file_id),1)[0];
                    $files->create_time = time();
                    $files->user = Yii::$app->user->id;
                    $files->audio_id = $_POST['id'];
                    $files->save();
                    $last = Yii::$app->getDb()->lastInsertID;
                    array_push($file_id,$last);
                }
                $result->file_id = join(',', $file_id);
                if($result->save()){
                    $id = $_POST['id'];
                    $mainSystem = AsrKeywordEndClassify::find()->where(['audio_id'=>null])->orWhere(['audio_id'=>$id])->asArray()->all();
                    $file_ids = explode(',',$result->file_id);
                    foreach ($file_ids as $value){
                        $f[] = AsrFiles::find()->where(['files_id'=>$value])->asArray()->one();
                    }
                    $result = AsrKeywordEndClassify::find()->where('keyword_classify_end_id='.$keyword_classify_end_id)->asArray()->one();
                    $data['current'] = $result;
                    $data['mainSystem'] = $mainSystem;
                    $data['file'] = $f;
                    echo $this->success($data);
                }

            }else{
                foreach($_POST['content'] as $key=>$v){
                    $file = AsrFiles::findOne($file_id[$key]);
                    $file->content = $v;
                    $file->save();
                }
                if($result->save()){
                    $id = $_POST['id'];
                    $mainSystem = AsrKeywordEndClassify::find()->where(['audio_id'=>null])->orWhere(['audio_id'=>$id])->asArray()->all();
                    $file_ids = explode(',',$result->file_id);
                    foreach ($file_ids as $value){
                        $f[] = AsrFiles::find()->where(['files_id'=>$value])->asArray()->one();
                    }
                    $result = AsrKeywordEndClassify::find()->where('keyword_classify_end_id='.$keyword_classify_end_id)->asArray()->one();
                    $data['current'] = $result;
                    $data['mainSystem'] = $mainSystem;
                    $data['file'] = $f;
                    echo $this->success($data);
                }
            }
        }
    }
    /**
     * Lists all AsrAudio models.
     * @return mixed
     */
    /**
     * 结束流程删除录音文件
     */
    public function actionEnddelete()
    {
        $file_id = $_POST['file_id'];
        $asr = AsrKeywordEndClassify::findOne($_POST['keyword_classify_end_id']);
        $classify_id = $asr->file_id;
        $b = explode(',',$classify_id);
        foreach($b as $key=>$v){
            if ($v == $file_id){
                unset($b[$key]);
            }
        }
        $id = join(',',$b);
        $asr->file_id = $id;
        $result = AsrFiles::findOne($file_id);
        $filepath = $result->filepath;
        if(!empty($filepath)){
            if(file_exists(Yii::$app->basePath . "/web" . $result->filepath)){
                unlink(Yii::$app->basePath . "/web" . $result->filepath);
            }
        }
        if($result->delete() && $asr->save()){
            $fil = null;
            if(!empty($id)){
                $fil = explode(',',$id);
            }

            if(!empty($fil)){
                foreach ($fil as $value){
                    $file[] = AsrFiles::find()->where(['files_id'=>$value])->asArray()->one();
                }
                echo $this->success($file);
            }else{
                $file = null;
                echo $this->success($file);
            }
        }
    }


    /**
     * @return string
     */
    public function actionIndex()
    {
        $audioClassify = AsrAudioClassify::find()->asArray()->all();

        $searchModel = new AsrAudioSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $this->pagesDo($dataProvider);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'audioClassify'=>$audioClassify,
        ]);
    }


    // 重命名
    public function actionNewname(){
        $id = $_POST['id'];
        $model = new AsrAudio();
        if($_POST){
            $audioname = $_POST['name'];
            $audioclassify = $_POST['audio_classify_id'];
            $result = $model->findOne($id);
            $result->name = $audioname;
            $result->audio_classify_id = $audioclassify;
            if($result->update()){
                echo 1;
            }
        }
    }
    /**
     * Creates a new AsrAudio model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $audioClassify = AsrAudioClassify::find()->all();
        if($_POST){
            $model = new AsrAudio();
            $model->name = $_POST['name'];
            $model->audio_classify_id = $_POST['audio_classify_id'];
            $keyword_classify = new AsrKeywordClassify();
            if($model->save()){
                $keyword_classify->audio_id = Yii::$app->getDb()->getLastInsertId();
                $keyword_classify->name = '开场白';
                $keyword_classify->start = 1;
                if($keyword_classify->save()){
                    echo Yii::$app->session->setFlash('success','保存成功');
                    return $this->redirect('index');
                }
            }
        }
        return $this->render('create',['audioClassify'=>$audioClassify]);
    }
    /**
     * 主流程节点切换
     */
    public function actionMain()
    {
        $mainSystem = AsrKeywordClassify::findOne($_POST['keyword_classify_id']);
        $name = AsrKeywordClassify::find()->where(['audio_id'=>$_POST['audio_id']])->one()->name;
        $file_id = explode(',',$mainSystem->file_id);
        foreach ($file_id as $value){
            $file[] = AsrFiles::find()->where(['files_id'=>$value])->asArray()->one();
        }

        $result =AsrKeyword::find()->where(['classify_id'=>$mainSystem->keyword_classify_id,'classify_type'=>0])->asArray()->all();
        //跳向话术节点
        foreach ($result as $v){
            $next[] = AsrKeywordClassify::find()->where(['keyword_classify_id'=>$v['next_classify_id']])->asArray()->one();
        }
        if(!empty($next)){
            $data['next'] = $next;
        }
        if(!empty($result)){
            $data['result'] = $result;
        }else{
            $data['result'] = '';
        }
        $data['score'] = $mainSystem->intent_score;
        $data['file'] = $file;
        $data['id'] = $_POST['audio_id'];
        $data['keyword_classify_id'] = $_POST['keyword_classify_id'];
        $data['name'] = $name;

        echo json_encode($data);
    }

    /**
     * 新增主流程节点
     */
    public function actionAdd(){
        $new_node = new AsrKeywordClassify();
        $new_node->audio_id = $_POST['id'];
        $new_node->name = '新的节点';
        $new_node->start = 1;
        if($new_node->save()){
            $id = $_POST['id'];
            $mainSystem = AsrKeywordClassify::find()->where(['audio_id'=>$id])->asArray()->all();
            echo $this->success($mainSystem);
        }
    }

    /**
     * 关键字查询
     */
    public function actionSearchkeyword(){
        $keyword_id = $_POST['keyword_id'];
        $content = AsrKeyword::find()->where(['keyword_id'=>$keyword_id])->asArray()->one();
        echo $content['content'];
    }
    /**
     * 意向标签名称保存
     */
    public function actionAddintentname(){
        $keyword_classify_id = $_POST['keyword_classify_id'];
        $intent_name = $_POST['intent_name'];
        $result = new AsrKeyword();
        $result->intent_name = $intent_name;
        $result->create_at = time();
        $result->classify_id = $keyword_classify_id;
        $result->classify_type = 0;
        if($result->save()){
            $result =AsrKeyword::find()->where(['classify_id'=>$keyword_classify_id,'classify_type'=>0])->asArray()->all();
            echo $this->success($result);
        }else{
            echo 0;
        }
    }
    /**
     * 意向标签删除
     */
    public function actionDelintentname(){
        $keyword_id = $_POST['keyword_id'];
        $result = AsrKeyword::findOne($keyword_id);
        if(!empty($result)){
            if($result->delete()){
                $result =AsrKeyword::find()->where(['classify_id'=>$_POST['keyword_classify_id'],'classify_type'=>0])->asArray()->all();
                echo $this->success($result);
            }
        }
    }

    /**
     * 下一步内容录音查询
     */
    public function actionMaincontents(){
        $keyword_id = $_POST['keyword_id'];
        $result = AsrKeyword::findOne($keyword_id);
        if(!empty($result)){
            $select3 = '';
            $ywlc = '';
            //下个节点id
            $next_classify_id = $result->next_classify_id;
            if(empty($next_classify_id)){
                echo 0;
                exit;
            }
            //下个节点类型
            $next_classify_type = $result->next_classify_type;
            //当前节点id
            $classify_id = $result->classify_id;
            if($next_classify_type==0){
                //下个节点
                $keyword_classify = AsrKeywordClassify::findOne($next_classify_id);
                //下个节点名称
                $keyword_classify_id = $keyword_classify->keyword_classify_id;
                //主流程节点
                $nodename = AsrKeywordClassify::find()->where(['audio_id'=>$_POST['audio_id']])->asArray()->all();
            }elseif ($next_classify_type==1){
                //下个节点
                $keyword_classify = AsrKeywordYwlcClassify::findOne($next_classify_id);
                //下个节点名称
                $keyword_classify_id = $keyword_classify->parent_id;
                //select3
                $select3 = $keyword_classify->id;
                //业务流程节点
                $nodename = AsrKeywordYwlcClassify::find()->select('id,name,audio_id,file_id')->where(['audio_id'=>$_POST['audio_id']])->andWhere(['parent_id'=>0])->asArray()->all();
                //
                $ywlc = AsrKeywordYwlcClassify::find()->select('id,name,audio_id,file_id')->where(['audio_id'=>$_POST['audio_id']])->andWhere(['parent_id'=>$keyword_classify->parent_id])->asArray()->all();
            }elseif ($next_classify_type==2){
                //下个节点
                $keyword_classify = AsrKeywordXtlcClassify::findOne($next_classify_id);
                //下个节点名称
                $keyword_classify_id = $keyword_classify->id;
                //系统流程节点
                $nodename = AsrKeywordXtlcClassify::find()->where(['parent_id'=>1])->asArray()->all();
            }elseif ($next_classify_type==3){
                //下个节点
                $keyword_classify = AsrKeywordEndClassify::findOne($next_classify_id);
                //下个节点名称
                $keyword_classify_id = $keyword_classify->keyword_classify_end_id;
                //结束流程节点
                $nodename = AsrKeywordEndClassify::find()->where(['audio_id'=>null])->orWhere(['audio_id'=>$_POST['audio_id']])->asArray()->all();
            }

            if(!empty($keyword_classify)){
                //查询录音 内容

                $file_id = explode(',',$keyword_classify->file_id);
                foreach($file_id as $v){
                    $file[] = AsrFiles::find()->where(['files_id'=>$v])->asArray()->one();
                }
                $data['nodename'] = $nodename;
                //语音内容
                $data['file'] = $file;
                $data['next_classify_type'] = $next_classify_type;
                $data['keyword_classify_id'] = $keyword_classify_id;
                $data['select3'] = $select3;
                $data['ywlc'] = $ywlc;
                echo $this->success($data);
            }else{
                echo 0;
            }
        }else{
            echo 0;
        }

    }

    /**
     * 下一步选择
     */

    public function actionSavenext(){
        if($_POST['selected']==0){
            $node = AsrKeywordClassify::find()->select('keyword_classify_id,name,audio_id,file_id')->where(['audio_id'=>$_POST['audio_id']])->asArray()->all();
            $data['node'] = $node;
            echo json_encode($data);
        }else if($_POST['selected']==1){
            $node = AsrKeywordYwlcClassify::find()->select('id,name,audio_id,file_id')->where(['audio_id'=>$_POST['audio_id']])->andWhere(['parent_id'=>0])->asArray()->all();
            $data['node'] = $node;
            echo json_encode($data);
        }else if($_POST['selected']==2){
            $node = AsrKeywordXtlcClassify::find()->select('id,name,audio_id,file_id')->where('parent_id>0')->asArray()->all();
            $data['node'] = $node;
            echo json_encode($data);
        }else if($_POST['selected']==3){
            $node = AsrKeywordEndClassify::find()->select('keyword_classify_end_id,name,audio_id,file_id')->where(['audio_id'=>null])->orWhere(['audio_id'=>$_POST['audio_id']])->asArray()->all();
            $data['node'] = $node;
            echo json_encode($data);
        }
    }

    /**
     * 下一步内容语音选择
     */
    public function actionTwoselect(){
        if($_POST['select']==0){
            $main = AsrKeywordClassify::findOne($_POST['classify_id']);
            $array = explode(',',$main->file_id);
            if(!empty($array)){
                foreach ($array as $v){
                    $file[] = AsrFiles::find()->where(['files_id'=>$v])->asArray()->one();
                }
                $data['file'] = $file;
                if(empty($file[0])){
                    echo 0;
                    exit;
                }
                echo $this->success($data);
            }else{
                echo 0;
            }
        }else if($_POST['select']==1){
            $yw = AsrKeywordYwlcClassify::findOne($_POST['classify_id']);
            $ywlc = AsrKeywordYwlcClassify::find()->where(['parent_id'=>$_POST['classify_id']])->asArray()->all();
            $data['ywlc'] = $ywlc;
            echo json_encode($data);

        }else if($_POST['select']==2){
            $system = AsrKeywordXtlcClassify::findOne($_POST['classify_id']);
            $array = explode(',',$system->file_id);
            if(!empty($array)){
                foreach ($array as $v){
                    $file[] = AsrFiles::find()->where(['files_id'=>$v])->asArray()->one();
                }
                $data['file'] = $file;
                if(empty($file[0])){
                    echo 0;
                    exit;
                }
                echo $this->success($data);
            }else{
                echo 0;
            }

        }else if($_POST['select']==3){
            $end = AsrKeywordEndClassify::findOne($_POST['classify_id']);
            $array = explode(',',$end->file_id);
            if(!empty($array)){
                foreach ($array as $v){
                    $file[] = AsrFiles::find()->where(['files_id'=>$v])->asArray()->one();
                }
                $data['file'] = $file;
                if(empty($file[0])){
                    echo 0;
                    exit;
                }
                echo $this->success($data);
            }else{
                echo 0;
            }
        }
    }
    /**
     * 业务select3内容语音
     */
    public function actionThreeselect(){
        $result = AsrKeywordYwlcClassify::find()->select('id,file_id,audio_id')->where(['id'=>$_POST['classify_id']])->asArray()->one();
        if(!empty($result)){
            $file_id = explode(',',$result['file_id']);
            foreach ($file_id as $v){
                $file[] = AsrFiles::find()->where(['files_id'=>$v])->asArray()->one();
            }
            $data['file'] = $file;
            if(empty($file[0])){
                echo 0;
                exit;
            }
            echo $this->success($data);
        }else{
            echo 0;
        }


    }
    /**
     * 下一步保存
     */
    public function actionSaveselect(){
        if(!empty($_POST['select3'])){
            $result = AsrKeyword::findOne($_POST['keyword_id']);
            $result->next_classify_id = $_POST['select3'];
            $result->next_classify_type = $_POST['select1'];
            if($result->save()){
                echo 1;
            }
        }else{
            $result = AsrKeyword::findOne($_POST['keyword_id']);
            $result->next_classify_id = $_POST['select2'];
            $result->next_classify_type = $_POST['select1'];
            if($result->save()){
                echo 1;
            }
        }
    }

    /**
     * 下一步清空maincontents
     */
    public function actionDelselect(){
        $result = AsrKeyword::findOne($_POST['keyword_id']);
        $result->next_classify_id = null;
        $result->next_classify_type = null;
        if($result->save()){
            echo 1;
        }
    }
    /**
     * 同意关键字保存
     */
    public function actionMainkeyword()
    {
        $result = AsrKeyword::findOne($_POST['keyword_id']);
        $result->content = $_POST['content'];
        $result->classify_type = 0;
        $result->classify_id = $_POST['main_keyword_classify'];
        if($result->save()){
            echo 1;
        }
    }
    /**
     * 拒绝关键字保存
     */
    public function actionMainkeywordnot()
    {
        $result = AsrKeyword::find()->where(['main_keyword_classify_id'=>$_POST['keyword_classify_id']])->andWhere(['status'=>0])->one();
        if(empty($result)){
            $keyword = new AsrKeyword();
            $keyword->name = $_POST['keyword'];
            $keyword->status = 0;
            $keyword->main_keyword_classify_id = $_POST['keyword_classify_id'];
            if($keyword->save()){
                echo 1;
            }
        }else{
            $result->name = $_POST['keyword'];
            if($result->save()){
                echo 2;
            }
        }

    }
    /**
     * 删除主流程节点
     */
    public function actionDel()
    {
        $v = 0;
        $result = AsrKeywordClassify::findOne($_POST['keyword_classify_id']);
        if(!empty($result->file_id)){
            $file_id = explode(',', $result->file_id);
            foreach ($file_id as $value){
                $res = AsrFiles::findOne($value);
                if(file_exists(Yii::$app->basePath . "/web" . $res->filepath)){
                    if(!empty($res->filepath)){
                        unlink(Yii::$app->basePath . "/web".$res->filepath);
                    }
                }
                $file[] = $res->delete();
            }
            foreach ($file as $value){
                if($value==1){
                    $v = 1;
                }
            }
            if($v == 1 && AsrKeywordClassify::findOne($_POST['keyword_classify_id'])->delete()){
                echo 1;
            }
        } else{
            if(AsrKeywordClassify::findOne($_POST['keyword_classify_id'])->delete()){
                echo 1;
            }
        }
    }


    /**
     * 主流程删除录音文件
     */
    public function actionMaindelete()
    {
        $file_id = $_POST['file_id'];
        $result = AsrFiles::findOne($file_id);
        if(file_exists(Yii::$app->basePath . "/web" . $result->filepath)){
            if(!empty($result->filepath)){
                unlink(Yii::$app->basePath . "/web".$result->filepath);
            }
        }
        if($result->delete()){
            $classify = AsrKeywordClassify::findOne($_POST['keyword_classify_id']);
            $file_id = explode(',',$classify->file_id);
            $file_id = array_diff($file_id,[$_POST['file_id']]);
            $classify->file_id = join(',',$file_id);
            $classify->save();
            if(!empty($file_id)){
                foreach ($file_id as $value){
                    $file[] = AsrFiles::find()->where(['files_id'=>$value])->asArray()->one();
                }
                echo $this->success($file);
            }else{
                $file = null;
                echo $this->success($file);
            }
        }
    }

    /**
     * @param $id 流程的id
     * @return string
     * 更新流程
     */
    public  function actionMainpost(){
        $id = $_POST['id'];
        if(empty($_POST['keyword_classify_id'])) {
            $mainSystem = AsrKeywordClassify::find()->where(['audio_id' => $id])->asArray()->all();
            //积分
            $score = $mainSystem[0]['intent_score'];

            $result = AsrKeyword::find()->where(['classify_id' => $mainSystem[0]['keyword_classify_id'], 'classify_type' => 0])->asArray()->all();

            $file_id = explode(',', $mainSystem[0]['file_id']);
            foreach ($file_id as $value) {
                $file[] = AsrFiles::find()->where(['files_id' => $value])->asArray()->one();
            }

            $keyword_classify_id = $mainSystem[0]['keyword_classify_id'];
            $data['keyword_classify_id'] = $keyword_classify_id;
            $data['mainSystem'] = $mainSystem;
            $data['file'] = $file;
            $data['id'] = $id;
            $data['score'] = $score;
            $data['result'] = $result;
            echo json_encode($data);
        }else{
            //当前节点
            $current = AsrKeywordClassify::find()->where(['keyword_classify_id' => $_POST['keyword_classify_id']])->asArray()->one();
            //意向
            $result = AsrKeyword::find()->where(['classify_id' => $_POST['keyword_classify_id'], 'classify_type' => 0])->asArray()->all();
            //文件
            $file_id = explode(',', $current['file_id']);
            foreach ($file_id as $value) {
                $file[] = AsrFiles::find()->where(['files_id' => $value])->asArray()->one();
            }
            $data['file'] = $file;
            $data['result'] = $result;
            $data['current'] = $current;
            echo $this->success($data);
        }
    }

    /**
     * @param $id
     * @return string
     */
    public function actionUpdate($id)
    {
        return $this->render('update', [
                'id' => $id,
            ]);
    }

    /**
     * 主流程保存
     */
    public function actionSaveclassify()
    {
        $keyword_classify_id = $_POST['keyword_classify_ids'];
        $result = AsrKeywordClassify::findOne($keyword_classify_id);
        $result->name = $_POST['name'];
        $result->intent_score = $_POST['score'];
        if(empty($result->file_id)){
            foreach($_POST['content'] as $key=>$v){
                $result = AsrKeywordClassify::findOne($keyword_classify_id);
                $result->name = $_POST['name'];
                $result->intent_score = $_POST['score'];
                if(empty($file_id)){
                    $file_id = [];
                }else{
                    $file_id = explode(',',$result->file_id);
                }
                $file = new AsrFiles();
                    $file->content = $v;
                    $file->create_time = time();
                    $file->user = Yii::$app->user->id;
                    $file->audio_id = $_POST['id'];
                    $file->save();
                    $last = Yii::$app->getDb()->lastInsertID;
                    array_push($file_id,$last);
                $result->file_id = join(',', $file_id);
                $result->save();
            }

                $id = $_POST['id'];
                $mainSystem = AsrKeywordClassify::find()->where(['audio_id'=>$id])->asArray()->all();
                $file_ids = explode(',',$result->file_id);
                foreach ($file_ids as $value){
                    $f[] = AsrFiles::find()->where(['files_id'=>$value])->asArray()->one();
                }
                $result = AsrKeywordClassify::find()->where('keyword_classify_id='.$keyword_classify_id)->asArray()->one();
                $data['current'] = $result;
                $data['mainSystem'] = $mainSystem;
                $data['file'] = $f;
                $keyword = AsrKeyword::find()->where(['classify_id'=>$result['keyword_classify_id'],'classify_type'=>0])->asArray()->all();
                $data['result'] = $keyword;
                echo $this->success($data);

        }else{
            $file_id = $result->file_id;
            $file_id = explode(',',$file_id);
            if(count($_POST['content'])>count($file_id)){
                foreach($file_id as $key=>$v){
                    $file = AsrFiles::findOne($v);
                    if(!empty($file)){
                        $file->content = $_POST['content'][$key];
                        $file->save();
                    }
                }
                $count = count($_POST['content'])-count($file_id);
                for($i=0; $i<$count; $i++){
                    $files = new AsrFiles();
                    $files->content = array_slice($_POST['content'],count($file_id),1)[0];
                    $files->create_time = time();
                    $files->user = Yii::$app->user->id;
                    $files->audio_id = $_POST['id'];
                    $files->save();
                    $last = Yii::$app->getDb()->lastInsertID;
                    array_push($file_id,$last);
                }
                $result->file_id = join(',', $file_id);
                if($result->save()){
                    $id = $_POST['id'];
                    $mainSystem = AsrKeywordClassify::find()->where(['audio_id'=>$id])->asArray()->all();
                    $file_ids = explode(',',$result->file_id);
                    foreach ($file_ids as $value){
                        $f[] = AsrFiles::find()->where(['files_id'=>$value])->asArray()->one();
                    }
                    $result = AsrKeywordClassify::find()->where('keyword_classify_id='.$keyword_classify_id)->asArray()->one();
                    $data['current'] = $result;
                    $data['mainSystem'] = $mainSystem;
                    $data['file'] = $f;
                    $keyword = AsrKeyword::find()->where(['classify_id'=>$result['keyword_classify_id'],'classify_type'=>0])->asArray()->all();
                    $data['result'] = $keyword;
                    echo $this->success($data);
                }

            }else{
                foreach($_POST['content'] as $key=>$v){
                    $file = AsrFiles::findOne($file_id[$key]);
                    $file->content = $v;
                    $file->save();
                }
                if($result->save()){
                    $id = $_POST['id'];
                    $mainSystem = AsrKeywordClassify::find()->where(['audio_id'=>$id])->asArray()->all();
                    $file_ids = explode(',',$result->file_id);
                    foreach ($file_ids as $value){
                        $f[] = AsrFiles::find()->where(['files_id'=>$value])->asArray()->one();
                    }
                    $result = AsrKeywordClassify::find()->where('keyword_classify_id='.$keyword_classify_id)->asArray()->one();
                    $data['current'] = $result;
                    $data['mainSystem'] = $mainSystem;
                    $data['file'] = $f;
                    $keyword = AsrKeyword::find()->where(['classify_id'=>$result['keyword_classify_id'],'classify_type'=>0])->asArray()->all();
                    $data['result'] = $keyword;
                    echo $this->success($data);
                }
            }
        }
    }
    /**
     * 主流程文件上传方法
     * @param $name
     * @return array
     */
    public function actionMainupload(){
        //file_id是否存在
        if ($_POST['file_id']=='undefined' || empty($_POST['file_id'])){
            $file = new AsrFiles();
            $file->name = $_FILES['filename']['name'];
            $file->filepath = $_FILES['filename']['name'];
            $file->filesize = $_FILES['filename']['size'];
            $file->create_time = time();
            $file->user = Yii::$app->user->id;
            $file->audio_id = $_POST['audio_id'];

            //文件上传存放的目录
            $dir = Yii::$app->basePath . "/web/uploads/yuyin/" . date("y") . '/' . date("md") . '/';
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
            }
            $names = time() . '_' . $_FILES['filename']['name'];
            $file->filepath = "/uploads/yuyin/" . date("y") . '/' . date("md") . "/" . $names;
            $result = AsrKeywordClassify::findOne($_POST['keyword_classify_id']);

            if (move_uploaded_file($_FILES['filename']['tmp_name'], $dir . $names) && $file->save()) {
                $last_id = Yii::$app->getDb()->lastInsertID;
                if(!empty($result->file_id)){
                    $file_id = explode(',',$result->file_id);
                    array_push($file_id,$last_id);
                    $result->file_id = join(',', $file_id);
                } else{
                    $result->file_id = $last_id;
                }
                if($result->save()){
                    $key = AsrKeywordClassify::findOne($_POST['keyword_classify_id']);
                    $file_id = explode(',',$key->file_id);
                    foreach ($file_id as $value){
                        $ff[] = AsrFiles::find()->where(['files_id'=>$value])->asArray()->one();
                    }
                    echo $this->success($ff);
                }
            }
        }else{
            //录音文件已经存在
            $files = AsrFiles::findOne($_POST['file_id']);
            if($files->filepath) {
                if (file_exists(Yii::$app->basePath . "/web" . $files->filepath)) {
                    if(!empty($files->filepath)){
                        unlink(Yii::$app->basePath . "/web" . $files->filepath);
                    }
                }
            }
            $files->filesize = $_FILES['filename']['size'];
            $files->name = $_FILES['filename']['name'];
            $files->user = Yii::$app->user->id;
            //文件上传存放的目录
            $dir = Yii::$app->basePath . "/web/uploads/yuyin/" . date("y") . '/' . date("md") . '/';
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
            }
            $name = time() . '_' . $_FILES['filename']['name'];
            $files->filepath = "/uploads/yuyin/" . date("y") . '/' . date("md") . "/" . $name;

            if (move_uploaded_file($_FILES['filename']['tmp_name'], $dir . $name) && $files->save()) {
                $key = AsrKeywordClassify::findOne($_POST['keyword_classify_id']);
                $file_id = explode(',',$key->file_id);
                foreach ($file_id as $value){
                    $ff[] = AsrFiles::find()->where(['files_id'=>$value])->asArray()->one();
                }
                echo $this->success($ff);
            }
        }

    }

    /**
     * 通过文件的实例来拿到文件的列表
     * @param $name
     * @return array
     */
    public static function getInstancesByName($name)
    {
        $files = self::loadFiles();
        if (isset($files[$name])) {
            return [new static($files[$name])];
        }
        $results = [];
        foreach ($files as $key => $file) {
            if (strpos($key, "{$name}[") === 0) {
                $results[$key] = new UploadedFile($file);
            }
        }

        return $results;
    }

    //拿到文件的方法
    private static $_files;

    /**
     * 将文件全部加载出来
     * @return array 文件的数组
     */
    private static function loadFiles()
    {
        if (self::$_files === null) {
            self::$_files = [];
            if (isset($_FILES) && is_array($_FILES)) {
                foreach ($_FILES as $class => $info) {
                    self::loadFilesRecursive($class, $info['name'], $info['tmp_name'], $info['type'], $info['size'], $info['error']);
                }
            }
        }
        return self::$_files;
    }

    /**
     * 加载文件
     * @param $key
     * @param $names
     * @param $tempNames
     * @param $types
     * @param $sizes
     * @param $errors
     */
    private static function loadFilesRecursive($key, $names, $tempNames, $types, $sizes, $errors)
    {
        if (is_array($names)) {
            foreach ($names as $i => $name) {
                self::loadFilesRecursive($key . '[' . $i . ']', $name, $tempNames[$i], $types[$i], $sizes[$i], $errors[$i]);
            }
        } elseif ((int) $errors !== UPLOAD_ERR_NO_FILE) {
            self::$_files[$key] = [
                'name' => $names,
                'tempName' => $tempNames,
                'type' => $types,
                'size' => $sizes,
                'error' => $errors,
            ];
        }
    }

    public function actionCreateLiucheng()
    {
        return $this->render('create-liucheng', [
            'url_base'=>$this->url_base
        ]);
    }

    /**
     * @param $id
     * @return string
     * 更新流程的名字以及种类
     */
    public function actionUpdateName($id)
    {
        $asrAudio = AsrAudio::findOne($id);
        if(Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            if($asrAudio->load($post) && $asrAudio->save()){
                echo Yii::$app->session->setFlash('success','修改成功！');
            };
        };
        return $this->actionUpdate($id);
    }


    /**
     * @param $id
     * @param $order
     * @return string
     * 显示更新流程的内容
     */
    public function actionUpdateIframe($id,$order)
    {
        $keywordids = AsrAkf::find()->select('keyword_id')->where(['order'=>$order,'audio_id'=>$id])->groupBy(['keyword_id'])->asArray()->all();
        $fileids = AsrAkf::find()->select('files_id')->where(['order'=>$order,'audio_id'=>$id])->groupBy(['files_id'])->asArray()->all();
        $start_end = AsrAkf::find()->select('start_end')->where(['order'=>$order,'audio_id'=>$id])->one()->start_end;
        $this->layout = false;
        return $this->render('update-iframe'
            ,[
                'audio_id' => $id,
                'start_end' => $start_end,
                'order' => $order,
                'keywordids'=>$keywordids,
                'fileids'=>$fileids,
                'base_url'=>$this->url_base
            ]
        );
    }

    /**
     * @return string
     * @throws \yii\db\Exception
     * 创建关键字
     */
    public function actionCreateKeyword()
    {
        $asrKeyword = new AsrKeyword();
        if ( Yii::$app->request->isPost){
            if ($this->transaction==null){
                $this->transaction= Yii::$app->getDb()->beginTransaction();//创建事务
            }
            $post = Yii::$app->request->post();
            //拿到audio_id
            $order = $post['order'];
            //拿到audio_id
            $audio_id = $post['audio_id'];
            //拿到新的关键字
            $asrKeywordName = $post['asrkeyword-name'][$order];
            $asrKeyword->name = $asrKeywordName;
            $asrKeyword->create_at = time();
            $asrKeyword->save();
            $asrKeywordId = Yii::$app->getDb()->getLastInsertId();
            $this->redis->set("asr_audio:".$audio_id.":asr_keyword:audio_id=".Yii::$app->getDb()->getLastInsertId(), serialize($asrKeyword->attributes));
            $this->redis->set("asr_audio:".$audio_id.":asr_keyword:name=".$asrKeyword->name, Yii::$app->getDb()->getLastInsertId());
            //拿到文件
            $asrFilesIds = $post['AsrFiles']['name'];
            //保存外键关联关系
            if(count($asrFilesIds)<=1){
                $asrFiles = (new AsrFiles())->find()->where('files_id>0')->one();
                $asrFilesIds[$asrFiles->files_id] = '';
            }
            foreach ($asrFilesIds as $k=>$v){
                if ($k!=0){
                    //表示这个关键字与文件是一起的，就需要在这里保存关键字与文件的关系
                    $asrAkf = new AsrAkf();
                    $asrAkf->audio_id = (int)$audio_id;
                    $asrAkf->keyword_id = (int)$asrKeywordId;
                    $asrAkf->files_id = (int)$k;
                    $asrAkf->order = (int)$order;
                    $asrAkf->save();
                    $this->redis->set("asr_audio:".$audio_id.":asr_akf:keyword_id=".$asrKeywordId, serialize($asrAkf->attributes));
                }
            }
            $this->transaction->commit();//提交事务
        }
        return $this->actionUpdateIframe($audio_id,$order);

    }


    public $transaction;

    /**
     * @return string
     * @throws \yii\db\Exception
     * 文件的新增
     */
    public function actionCreateFile()
    {
        if ( Yii::$app->request->isPost){
            if ($this->transaction==null){
                $this->transaction= Yii::$app->getDb()->beginTransaction();//创建事务
            }
            $post = Yii::$app->request->post();
            //拿到audio_id
            $order = $post['order'];
            //拿到audio_id
            $audio_id = isset($post['audio_id'])?$post['audio_id']:0;
            //拿到asr_keyword
            if(!isset($post['AsrKeyword'])){
                $asrKeywordModel = (new AsrKeyword())->find()->where('keyword_id>0')->one();
                $asrKeyword[$asrKeywordModel->keyword_id] = '';
            }else{
                $asrKeyword =  $post['AsrKeyword']['name'];
            }
            //上传文件
            if(isset($post['AsrFiles'])){
                $asrFiles = new AsrFiles();
                $files = self::getInstancesByName("AsrFiles");
                $asrFiles->file = $files;
                $asrFilesIds = UploadFiles::upload($asrFiles);//将拿到的
                $this->redis->set("asr_audio:".$audio_id.":asr_file:files_id=".Yii::$app->getDb()->getLastInsertId(),serialize($asrFiles->attributes));
            }
            //保存外键关联关系
            foreach ($asrFilesIds as $k=>$v){
                foreach ($asrKeyword as $k1=>$v1){
                    //表示这个关键字与文件是一起的，就需要在这里保存关键字与文件的关系
                    $asrAkf = new AsrAkf();
                    $asrAkf->audio_id = (int)$audio_id;
                    $asrAkf->keyword_id = (int)$k1;
                    $asrAkf->files_id = (int)$v;
                    $asrAkf->order = $order;
                    $asrAkf->save();
                    $this->redis->set("asr_audio:".$audio_id.":asr_akf:akf_id=".Yii::$app->getDb()->getLastInsertId(), serialize($asrAkf->attributes));
                }
            }
            $this->transaction->commit();//提交事务
        }
        return $this->actionUpdateIframe($audio_id,$order);

    }

    /**
     * @return string
     * 关键字的删除
     */
    public function actionDeleteKeyword()
    {
        if ( Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            //拿到audio_id
            $order = $post['order'];
            //拿到audio_id
            $audio_id = $post['audio_id'];
            //拿到要删除的关键字
            $delete_keyword = $post['delete_keyword'];
            $this->redis->del("asr_audio:".$audio_id.":asr_keyword:keyword_id=".$delete_keyword);
            $this->redis->del("asr_audio:".$audio_id.":asr_keyword:name=".(AsrKeyword::findOne($delete_keyword)->name()));
            AsrKeyword::deleteAll(['keyword_id'=>$delete_keyword]);
        }
        return $this->actionUpdateIframe($audio_id,$order);

    }

    //文件的删除
    public function actionDeleteFile()
    {
        if ( Yii::$app->request->isPost){
            try{
                $post = Yii::$app->request->post();
                //拿到audio_id
                $order = isset($post['order']) ? $post['order'] : 0;
                //拿到audio_id
                $audio_id = isset($post['audio_id']) ? $post['audio_id'] : 0;
                //拿到要删除的关键字
                $delete_file = isset($post['delete_file'])? $post['delete_file'] : 0;
                $file = AsrFiles::findOne($delete_file);
                $filePath = $file->filepath;
                if (AsrFiles::deleteAll(['files_id'=>$delete_file])){
                    $this->redis->del("asr_audio:".$audio_id.":asr_file:files_id=".$delete_file);
                    $path =  str_replace("\\","/",$this->absBasePath."/web".$filePath);
                    unlink($path);
                };
            }catch (\Exception $exception){
                echo Yii::$app->session->setFlash('error','删除文件失败！');
            }
        }
        return $this->actionUpdateIframe($audio_id,$order);
    }

    //文件的新增
    public function actionCreateFile2()
    {
        if ( Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            //拿到audio_id
            $audio_id = $post['audio_id'];
            //上传文件
            if(isset($post['AsrFiles'])){
                $asrFiles = new AsrFiles();
                $files = self::getInstancesByName("AsrFiles");
                $asrFiles->file = $files;
                $asrFilesIds = UploadFiles::upload($asrFiles);//将拿到的
                $this->redis->set("asr_audio:".$audio_id.":asr_file:files_id=".Yii::$app->getDb()->getLastInsertId(),serialize($asrFiles->attributes));
            }
            //保存外键关联关系
            foreach ($asrFilesIds as $k=>$v){
                //表示这个关键字与文件是一起的，就需要在这里保存关键字与文件的关系
                $asrAkf = new AsrAkf();
                $asrAkf->audio_id = (int)$audio_id;
                $asrAkf->files_id = (int)$v;
                $asrAkf->order = 0;
                $asrAkf->save();
                $this->redis->set("asr_audio:".$audio_id.":asr_akf:akf_id=".Yii::$app->getDb()->getLastInsertId(), serialize($asrAkf->attributes));
            }
        }
        return $this->actionUpdateIframe2($audio_id);

    }

    //文件的删除
    public function actionDeleteFile2()
    {
        if ( Yii::$app->request->isPost){
            $post = Yii::$app->request->post();
            //拿到audio_id
            $audio_id = isset($post['audio_id']) ? $post['audio_id'] : 0;
            //拿到要删除的关键字
            $delete_file = isset($post['delete_file'])? $post['delete_file'] : 0;
            $file = AsrFiles::findOne($delete_file);
            $filePath = $file->filepath;
            if (AsrFiles::deleteAll(['files_id'=>$delete_file])){
                $this->redis->del("asr_audio:".$audio_id.":asr_file:files_id=".$delete_file);
                $path =  str_replace("\\","/",$this->absBasePath."/web".$filePath);
                unlink($path);
            };
        }
        return $this->actionUpdateIframe2($audio_id);
    }

    public function actionUpdateIframe2($id)
    {
        $asrAudio = AsrAudio::findOne($id);
        //拿到的是非重复的order
        $orders = AsrAkf::find()->select("order")->where('audio_id='.$asrAudio->audio_id)->groupBy(["order"])->asArray()->all();
        $asrAkfsOrder = [];//排序的 数组列表
        $keyword_ids_arr = [];//关键字 数组列表
        $no_keyword_ids_arr = [];//非关键字 数组列表
        foreach ($orders as $k=>$v){
            //拿到的是非重复的keword_id
            if ($v['order']!=="0"){
                $keyword_ids = AsrAkf::find()->select("keyword_id")->where(["order"=>$v['order']])->groupBy(["keyword_id"])->asArray()->all();
                $keyword_ids_arr[$v['order']] = $keyword_ids;
            }
            if ($v['order']==="0"){
                $no_keyword_ids_arr[$v['order']] = AsrAkf::find()->select("*")->where("keyword_id is null")->asArray()->all();
            }
            $asrAkfsOrder[$v['order']] = AsrAkf::find()->select("*")->where(['order'=>$v['order'],'audio_id'=>$id])->asArray()->all();
        }

//        if ($asrAudio->load(Yii::$app->request->post())) {
//
//            echo Yii::$app->session->setFlash('success','修改成功！');
//            return $this->redirect(['update', 'id' => $asrAudio->audio_id]);
//        }
        $fileids = AsrAkf::find()->select('files_id')->where(['order'=>0,'audio_id'=>$id,'start_end'=>2])->groupBy(['files_id'])->asArray()->all();
        $this->layout = false;
        return $this->render('update-iframe2', [
            'model' => $asrAudio,
            'base_url' => $this->url_base,
            'audio_id' => $id,
            'fileids'=>$fileids,
            'base_url'=>$this->url_base
        ]);
    }

    /**
     * Deletes an existing AsrAudio model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        echo Yii::$app->session->setFlash('danger','删除成功！');
        return $this->redirect(['index']);
    }

    /**
     * Finds the AsrAudio model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return AsrAudio the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = AsrAudio::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
